<template>
  <div class="presentedList">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage('/presentManager')" ref="header">
      赠送酒水查询<a slot="right" @click="goToPage('/presentStatistics')" >赠送统计</a>
    </x-header>
    <div class="topHolder"></div>
    <box gap="1rem 0.8rem 0.8rem">
      <div class="filterArea" ref="filterArea">
        <div class="filterItem"><x-button @click.native="showUsersByDepart = true" type="default" v-html="usersByDepartText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="changeUsersByDepartText();refreshList()" :show.sync="showUsersByDepart" :show-cell="false" :data="usersByDepart" :columns="2" v-model="choosenDepartAndUser" ref="usersByDepart" class="btn_popup-picker"></popup-picker>
    </box>
    <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller" >
      <div class="presentedList">
        <a v-for="(item,index) in presentedList" :key="index" @click="toDetail(item.PRESENT_ID)">
          <form-preview class="formPreviewList label" :class="[getStateClass(item.STATE)]" :header-label="'赠送类型：' + getType(item.TYPE)" :header-value="getState(item.STATE)" :body-items="getBody(item)"></form-preview>
        </a>
        <div class="listNoItem" v-if="presentedList.length <= 0">暂无赠送</div>
      </div>
    </scroller>
  </div>
</template>

<script>
  import {XButton, Box, PopupPicker, FormPreview, Scroller, numberComma } from 'vux'
  import {getUsersByDepart,getPresentedIdList,getPresentByIds} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'presentedList',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        usersByDepartText:'',
        showUsersByDepart: false,
        choosenDepartAndUser:['allDepart','allPerson'],
        presentedList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage: 0,
        totalItems:0,
        pageSize:8,
        onFetching:true
      }
    },
    components:{
      XButton,
      Box,
      PopupPicker,
      FormPreview,
      Scroller
    },
    computed:{
      authority(){
        return this.$store.getters.getAuthorityPresent
      },
      usersByDepart:{
        get(){
          return this.$store.getters.getUsersByDepart_present
        },
        set(value){
          this.$store.commit('updateUsersByDepart_present', value)
        }
      }
    },
    methods:{
      goToPage(url){
        this.$router.push({path:url})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      getType(type){
        switch (type) {
          case 0:return '售卖库存';break
          case 1:return '存酒库存';break
          case 2:return '过期酒水';break
          case 3:return '美女台赠送';break
          case 4:return '会员卡赠送';break
          default:return '无类型';break
        }
      },
      getState(state){
        switch (state) {
          case 0:return '待赠送';break
          case 1:return '成功赠送';break
          case 2:return '不同意赠送';break
          default:return '无状态';break
        }
      },
      getStateClass(state){
        switch (state) {
          case 0:return 'orange';break
          case 1:return 'green';break
          case 2:return 'red';break
          default:return 'gray';break
        }
      },
      getBody(item){
        let list = []
        list.push({label:'请求时间',value:item.REQUEST_DATETIME})
        list.push({label:'发起赠送人',value:item.PRESENTER + '-' + item.present_DEPARTMENT})
        list.push({label:'点击查看详情>>',value:''})
        /*if(item.REMARK != '')
          list.push({label:'备注',value:item.REMARK})*/
        return list
      },
      toDetail(id){
        this.$router.push({name:'赠送酒水详情',params:{presentId:id}})
      },
      refreshList(params){
        this.loadingStatus = true
        this.presentedList = []
        this.currentPage = 0
        let reqParams = {
          choosenDepartAndUser:this.choosenDepartAndUser,
          authority:this.authority.view
        }
        getPresentedIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller) {
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getPresentedIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getPresentedIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getPresentByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.presentedList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.presentedList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getPresentByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getPresentByIds catch info:',err)})
          }, 1)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
          outHeight = this.$refs.header.$el.offsetHeight + this.$refs.filterArea.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      changeUsersByDepartText(text){
        this.usersByDepartText = text?(text+'<i class=\'iconfont icon-xiangxia2\'></i>'):(this.$refs.usersByDepart&&this.$refs.usersByDepart.getNameValues().replace(/ /g,' / ')+'<i class=\'iconfont icon-xiangxia2\'></i>')
      }
    },
    mounted(){
      return new Promise((resolve,reject)=>{
        if(this.usersByDepart.length <= 0)
          getUsersByDepart(this.authority.view).then((res)=>{
            if(res.status == 'success'){
              this.usersByDepart = res.data
              //this.$store.commit('updateUsersByDepart_present', res.data)
            }else if(res.status == 'error') {
              message({message:res.msg,type:'error'})
              console.log('getUsersByDepart error info:', res.msg)
            }
            resolve()
          }).catch((err)=>{console.log('getUsersByDepart catch info:',err)})
        else resolve()
      }).then(()=>{
        switch (this.authority.view) {
          case 'self':
            this.choosenDepartAndUser = [this.usersByDepart[0].value,this.usersByDepart[1].value]
            break
          case 'depart':
            this.choosenDepartAndUser = [this.usersByDepart[0].value,'entire_' + this.usersByDepart[0].value]
            break
          default:
            this.choosenDepartAndUser = ['allDepart','allPerson']
        }
        setTimeout(()=>{this.changeUsersByDepartText(this.usersByDepart[0].name + ' / ' + this.usersByDepart[1].name)},200)
        this.refreshList({callback:()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss" scoped>
  .presentedList{

  }
</style>
